const path = require('path')

const Koa = require('koa')
const koaStatic = require('koa-static')

const errHandler = require('./errHandler')
const router = require('../router/index')

const app = new Koa()


// 暴露静态资源文件，用于前端获取图片或者其他文件
app.use(koaStatic(path.join(__dirname, "../public/upload")))

// 统一处理options预请求
app.use(async (ctx, next) => {
    ctx.set('Access-Control-Allow-Origin', '*')
    ctx.set('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild,X-Token',)
    ctx.set('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS')
    if (ctx.method == 'OPTIONS') {
        ctx.body = 200
    } else {
        await next()
    }
})

// 路由注册
app.use(router.routes())

// 统一错误处理
app.on('error', errHandler)

module.exports = app